<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Externalbuy_m extends CI_Model {
    function __construct()
    {
        parent::__construct();
    }
    function saveExternalBuy($buyId)
    {
        //先判断是否存在！
        $sku = trim($this->input->post('sku'));
        $rs = $this->fun->getdatabasesdetail('db_external_buy'," AND sku='".$sku."'");
        if(!$buyId){
            if($rs)
            {
                die('SKU已经存在！');
            }
        }else{
            $rsss = $this->fun->getdatabasesdetail('db_external_buy'," AND id != '{$buyId}' AND sku='".$sku."'");
            if($rsss){
                echo "所修改的SKU已经存在!";exit;
            }
        }
        //保存相关信息
        $postdata['p_parent_name']	= $this->input->post('goods_name');
        $postdata['p_en_goods_name']	= trim($this->input->post('en_goods_name'));
        $postdata['p_costprice']	= $this->input->post('costprice');
        $postdata['supplier']  =trim($this->input->post('supplier'));
        $postdata['contactperson']  =trim($this->input->post('contactperson'));
        $postdata['phone']  =trim($this->input->post('phone'));
        $postdata['address']  =trim($this->input->post('address'));
        $postdata['sizeinfo']	= trim($this->input->post('sizeinfo'));
        $postdata['fabricinfo']  = trim($this->input->post('fabricinfo'));
        $postdata['memo']  = trim($this->input->post('memo'));
        $postdata['buy_days'] = trim($this->input->post('buy_days'));//采购天数

        //保存
        if(trim($this->input->post('sellprice'))){
            $postdata['p_sellprice']	= trim($this->input->post('sellprice'));
        }

        $postdata['platId']	= implode(",",$this->input->post('platId'));

        $postdata['developer']  = trim($this->input->post('developer')); //开发者
        $postdata['protector']  = trim($this->input->post('protector')); //维护者
        //重量 长宽高
        if(trim($this->input->post('weight'))){
            $postdata['weight'] = trim($this->input->post('weight'));
        }
        if(trim($this->input->post('length'))){
            $postdata['length'] = trim($this->input->post('length'));
        }
        if(trim($this->input->post('width'))){
            $postdata['width'] = trim($this->input->post('width'));
        }
        if(trim($this->input->post('heigth'))){
            $postdata['heigth'] = trim($this->input->post('heigth'));
        }

        //$where = array('sku' => $sku);
        //$rsdb = $this->db->get_where('db_product_buy',$where)->result_array();
        if($buyId){
            //追加日志信息
            $sql = "SELECT * FROM db_external_buy WHERE id = {$buyId} ";
            $result = $this->db->query($sql)->row_array();
            if($result['status']==1){
                $postdata['p_bigclassid']	= $this->input->post('bigclassID');
                $postdata['p_secondclassid']= $this->input->post('secondclassID');
                $postdata['p_threeclassid'] = $this->input->post('ThreeclassID');
                $postdata['sku']	= strtoupper($sku);	//全部大写
            }
            $msg = "";
            if($result['developer']==$postdata['developer']){
            }else{
                $msg .= "开发者由：{$result['developer']},更改为：{$postdata['developer']} "."<br/>";
            }
            if($result['protector']==$postdata['protector']){
            }else{
                $msg .= "维护者由：{$result['protector']},更改为：{$postdata['protector']} "."<br/>";
            }
            if($result['address']==$postdata['address']){
            }else{
                $msg .= "采购链接由：{$result['address']},更改为：{$postdata['address']} "."<br/>";
            }
            if($msg){
                $arr_logs['createtime'] = date("Y-m-d H:i:s");
                $arr_logs['pid'] = $buyId;
                $arr_logs['goods_code'] = $result['sku'];
                //$arr_logs['goods_code'] = $postdata['sku'];
                $arr_logs['details'] = $msg;
                $arr_logs['username'] = $_COOKIE['username'];
                $arr_logs['userid'] = $_COOKIE['userid'];
                $this->db->insert('db_externalbuy_log', $arr_logs);
            }

            //更新母商品
            $this->db->update('db_external_buy', $postdata, 'id=' . $buyId);
            $parentID = $buyId;

        }else{
            $postdata['status']  = 1; //样品采购
            $postdata['p_bigclassid']	= $this->input->post('bigclassID');
            $postdata['p_secondclassid']= $this->input->post('secondclassID');
            $postdata['p_threeclassid'] = $this->input->post('ThreeclassID');
            $postdata['sku']	= strtoupper($sku);	//全部大写
            //插入
            $postdata['createTime']		= date("Y-m-d H:i:s");
            $postdata['createID']		= $_COOKIE["userid"];
            $postdata['createName']	= $_COOKIE["username"];
            $this->db->query($this->db->insert_string('db_external_buy', $postdata));
            $parentID = $this->db->insert_id();

            //追加日志信息
            $msg = "外采购商品添加成功";
            $arr_logs['createtime'] = date("Y-m-d H:i:s");
            $arr_logs['pid'] = $parentID;
            $arr_logs['goods_code'] = $postdata['sku'];
            $arr_logs['details'] = $msg;
            $arr_logs['username'] = $_COOKIE['username'];
            $arr_logs['userid'] = $_COOKIE['userid'];
            $this->db->insert('db_externalbuy_log', $arr_logs);

        }

        return $parentID;
    }

    function saveExternalBuygoods($parentID,$buyId="",$arr_subsku=array())
    {
        if($arr_subsku){
            $subsku = $arr_subsku; //传输子sku数组过来
            $subskuinfo = array();
        }else{
            $subsku =  $this->input->post('subsku');
            $subskuinfo = $this->input->post('subskuinfo'); //子sku备注信息
        }

        $postdata = "";
        //$subskuList = $this->db->get_where('db_product_buygoods','del_flag = 0 AND pid='.$parentID)->result_array();

        if(count($subsku)>0)	//填写了子类商品
        {
            $subsku = array_unique(array_filter($subsku));

            $str_sizeinfo = "";
            foreach($subsku as $key=>$rs)
            {
                $postdata["subsku"] = trim(strtoupper($rs));
                $postdata['memo'] = trim($subskuinfo[$key]);

                //判断该sku是否存在，或者是否为别的商品的子sku
                $costr = $this->fun->iscognatelist(trim(strtoupper($rs)));
                if( $costr != false)
                {
                    echo $costr;
                    die;
                }
                $results = $this->fun->getdatabasesdetail('db_goods'," AND goods_sku='".trim(strtoupper($rs))."'");
                if($results)
                {
                    continue;//如果存在sku则不保存
                }
                $str_sizeinfo.= $postdata["subsku"].":".$postdata['memo']."\n";
                if($buyId){
                    $this->db->update("db_external_buygoods",array('subsku'=>$rs,'memo'=>trim($subskuinfo[$key])),"id=".$key);
                    continue;
                }else{
                    $postdata["pid"] = $parentID;
                    $this->db->query($this->db->insert_string('db_external_buygoods', $postdata));
                }

            }
            if($str_sizeinfo){
                $this->db->update("db_external_buy",array('sizeinfo'=>$str_sizeinfo),"id=".$parentID);
            }
        }

        }


    //已完成  保存
    function saveparent($id,$buyId = "")
    {
        //更新
        $subsku = $this->input->post('subsku'); //子sku信息
        $subskuinfo = $this->input->post('subskuinfo');

        //商品属性  [cat_id] => 7 [cat_name] => 衣服  [cat_id] => 8 [cat_name] => 鞋子
        // [cat_id] => 12 [cat_name] => 玩具   [cat_id] => 13 [cat_name] => 其他
        $goodstypeID = $this->input->post('goodstypeID');
        if($goodstypeID==7){ //衣服
            $arr_attr_values9 = $this->input->post("attr_values9"); //欧美
            $arr_attr_values2 = $this->input->post("attr_values2"); //XL
            $arr_attr_values1 = $this->input->post("attr_values1"); //女性

        }
        if($goodstypeID==8){//鞋子
            $arr_attr_values4 = $this->input->post("attr_values4"); //红色 颜色
            $arr_attr_values5 = $this->input->post("attr_values5"); //20 尺码
        }
        if($goodstypeID==12){//玩具
            $arr_attr_values7 = $this->input->post("attr_values7"); //型号
            $arr_attr_values8 = $this->input->post("attr_values8"); //版本号
        }
        if($goodstypeID==13){//其他   不用做额外操作了
        }
        //$sku = trim($this->input->post('skuId')); //主商品编号
        //$skufile = $_FILES["userfile"];


        //已完成
        $sql = "SELECT * FROM db_external_buy WHERE del_flag = 0 AND id= {$id} ";
        $rs = $this->db->query($sql)->row_array();

        //先判断是否存在！

        /**
        $results = $this->fun->getdatabasesdetail('db_goods_parent'," AND p_parent_sku='".$rs['sku']."'");
        if($results)
        {
            die('SKU已经存在！');
        }**/

        $postdata['p_parent_sku']	= strtoupper($rs['sku']);	//全部大写
        $postdata['p_parent_name']	= $rs['p_parent_name'];
        $postdata['p_en_goods_name']	= $rs['p_en_goods_name'];
        $postdata['p_bigclassid']	= $rs['p_bigclassid'];
        $postdata['p_secondclassid']= $rs['p_secondclassid'];
        $postdata['p_threeclassid'] = $rs['p_threeclassid'];
        $postdata['p_costprice']	= $rs['p_costprice'];
        $postdata['p_procurement']  = 15;
        $postdata['p_inventory_day']= 15;
        $postdata['p_weight']		= $rs['weight'];
        $postdata['p_pd_length']	= $rs['length'];
        $postdata['p_pd_width']		= $rs['width'];
        $postdata['p_pd_height']	= $rs['heigth'];
        $postdata['memo']           = $rs['memo'];
        $postdata['businessman']     = $rs['supplier'];
        $postdata['businessmanline']     = $rs['address'];
        $postdata['fabricinfo']  = $rs['fabricinfo'];
        $postdata['p_updatetime'] = date("Y-m-d H:i:s");
        $postdata['p_buyer'] = $rs['developer'];
		$postdata['standard'] = $rs['sizeinfo'];
        $postdata['p_checkman'] = $rs['developer'];
        $postdata['p_sale_status'] = 1;
        $postdata['p_supplier'] = 3;
        //采购天数
        if($rs['buy_days']){
            $postdata['p_procurement'] = $rs['buy_days'];
        }

        if($goodstypeID){
            $postdata['p_goodstypeID'] = $goodstypeID;
        }

        if($rs['p_sellprice']){
            $postdata['p_sellprice'] = $rs['p_sellprice'];
        }
        $postdata['p_pd_declare_value'] = 60;

        $where = array('p_parent_sku' => $rs['sku']);
        $rsdb = $this->db->get_where('db_goods_parent',$where)->result_array();

        if(count($rsdb)==0)	//没有母商品
        {
            $postdata['p_intime']		=time();
            $postdata['p_createID']		=$_COOKIE["userid"];
            $postdata['p_createUser']	=$_COOKIE["username"];
            $this->db->query($this->db->insert_string('db_goods_parent', $postdata));
            $parentID = $this->db->insert_id();
        }else{
            //若存在则不更新
            //$this->db->update('db_goods_parent', $postdata, 'p_parent_id=' . $rsdb[0]["p_parent_id"]);
            $parentID = $rsdb[0]["p_parent_id"];
        }

        //更新商品表 如果存在子商品的话
        if(count($subsku)){
            $subsku = array_unique(array_filter($subsku));

            $str_sizeinfo = "";
            foreach($subsku as $key=>$rv)
            {
                $post['pid'] = $id;
                $post["subsku"] = trim(strtoupper($rv));
                $post['memo'] = trim($subskuinfo[$key]);

                //判断该sku是否存在，或者是否为别的商品的子sku
                $costr = $this->fun->iscognatelist(trim(strtoupper($rv)));
                if( $costr != false)
                {
                    //echo $costr;
                    //die;
                    continue;
                }
                $results = $this->fun->getdatabasesdetail('db_goods'," AND goods_sku='".trim(strtoupper($rv))."'");
                if($results)
                {
                    continue;//如果存在sku则不保存
                }

                $imagesfile = $_FILES["userfile"]["tmp_name"][$key]; //图片文件
                if($imagesfile){
                    $images_content = file_get_contents($imagesfile);
                    $upload_path = 'uploads/externalbuy/'.date("Ymd")."";
                    $dir = dirname(__FILE__) . "/../../".$upload_path;
                    !is_dir($dir) && @mkdir($dir, 0755, true);
                    $filename = date("YmdHms_", time()) . rand(100000, 999999);
                    $file_suffix = ".jpg";
                    $filepath = $upload_path."/".$filename.$file_suffix;

                    $img = array();
                    if(@file_put_contents($filepath, $images_content)>0){
                        $pathst = str_replace(dirname(__FILE__) . "/../../", '',$filepath);
                        //$img["images_url"] = "/".$pathst;  //图片文件
                        $post["sub_images_url"] = "/".$pathst;  //图片文件
                        //生成缩略图
                        $this->load->library('image_lib');
                        $config['image_library'] = 'gd2';
                        $config['source_image'] = $filepath;
                        //print_r($data['thumb']);exit;
                        //$config['new_image'] =  ""; //默认路径在同级目录
                        $config['create_thumb'] = TRUE;
                        $config['maintain_ratio'] = TRUE;
                        $config['width']     = 150;
                        $config['height']   = 150;
                        $this->image_lib->initialize($config);
                        $this->image_lib->resize();
                        $filepath_thumb =  $upload_path."/".$filename."_thumb".$file_suffix;
                        $thumb_url = str_replace(dirname(__FILE__) . "/../../", '',$filepath_thumb);
                        //$img["thumb_url"] = "/".$thumb_url;  //缩略图文件
                        $post["sub_thumb_url"] = "/".$thumb_url;  //缩略图文件
                        $post["filename"] = basename($filepath);
                        $post["filesize"] = filesize($filepath);

                    }
                    //更新数据表
                    /**
                    $img["uid"] = $parentID;
                    //$img["images_url"] = $rs;
                    //$img["thumb_url"] = $thumb;
                    $img["createUser"] = $_COOKIE["username"];
                    $img["instime"] = time();
                    $img["filename"] = basename($filepath);
                    $img["filesize"] = filesize($filepath);
                    $this->db->insert('db_externalbuy_images',$img);
                     * */

                }
                if(trim($postdata['memo'])){
                    $str_sizeinfo.= $postdata["subsku"].":".$postdata['memo']."\n";
                }
                /**
                if($buyId){
                    $this->db->update("db_external_buygoods",array('subsku'=>$rs,'memo'=>trim($subskuinfo[$key])),"id=".$key);
                    continue;
                }else{
                    $postdata["pid"] = $id;
                    $this->db->query($this->db->insert_string('db_external_buygoods', $post));
                }**/

                $arr_rs = $this->fun->getdatabasesdetail('db_external_buygoods'," AND pid = {$id} AND del_flag = 0 AND subsku='".trim(strtoupper($rv))."'");
                if($arr_rs)
                {
                    continue;//如果存在sku则不保存
                }
                $arr_property = array();
                if($goodstypeID==7){ //衣服
                    $arr_property[1] = $arr_attr_values1[$key];
                    $arr_property[2] = $arr_attr_values2[$key];
                    $arr_property[9] = $arr_attr_values9[$key];
                    $post['goods_attr_id'] = 7;
                    $post['attr_value'] = serialize($arr_property);
                }
                if($goodstypeID==8){ //鞋子
                    $arr_property[4] = $arr_attr_values4[$key];
                    $arr_property[5] = $arr_attr_values5[$key];
                    $post['goods_attr_id'] = 8;
                    $post['attr_value'] = serialize($arr_property);
                }
                if($goodstypeID==12){ //玩具
                    $arr_property[7] = $arr_attr_values7[$key];
                    $arr_property[8] = $arr_attr_values8[$key];
                    $post['goods_attr_id'] = 12;
                    $post['attr_value'] = serialize($arr_property);
                }
                if($goodstypeID){ //玩具
                    $post['goods_attr_id'] = $goodstypeID;
                }

                $this->db->query($this->db->insert_string('db_external_buygoods', $post));

                //更新db_goods_attr 表

            }
            if($str_sizeinfo){
                $str_sizeinfo.= $rs['sizeinfo'];
                $this->db->update("db_external_buy",array('sizeinfo'=>$str_sizeinfo),"id=".$parentID);
            }

        }

        //获取外采购商品开发人员对应的仓库
        $str_warehouse = $this->config->item('temporary_warehouse');
        $arr_warehouse = explode("\n",$str_warehouse);
        $arr_persons = array(); //维护人员
        $arr_positions = array();//具体仓库位置
        foreach($arr_warehouse as $k=>$v){
            $arr_value = explode("|",trim($v));
            $arr_persons[$k] = $arr_value[0];
            $arr_positions[$k]=$arr_value[1];
        }
        //操作 商品列表等
        $sql_buygoods = "SELECT * FROM db_external_buygoods WHERE del_flag = 0 AND pid = {$rs['id']} ";
        $rs_buygoods  = $this->db->query($sql_buygoods)->result_array();
        if(!empty($rs_buygoods)){
            foreach($rs_buygoods as $k=>$v){
                //更新商品表 商品库存
                $arr_goods = array();
                $arr_goods['goods_parentID'] = $parentID;
                $arr_goods['goods_parent_sku'] = $rs['sku'];
                $arr_goods['goods_sku'] = $v['subsku'];  //子sku
                $arr_goods['goods_name'] = $rs['p_parent_name'];
                $arr_goods['en_goods_name'] = $rs['p_en_goods_name'];
                $arr_goods['g_bigclassid'] = $rs['p_bigclassid'];
                $arr_goods['g_secondclassid'] = $rs['p_secondclassid'];
                $arr_goods['g_threeclassid'] = $rs['p_threeclassid'];
                $arr_goods['g_costprice'] = $rs['p_costprice'];
                $arr_goods['g_procurement'] = 15;
                $arr_goods['g_procurement'] = 15;
                $arr_goods['g_weight'] =  $rs['weight'];
                $arr_goods['g_pd_length'] = $rs['length'];
                $arr_goods['g_pd_width'] = $rs['width'];
                $arr_goods['g_pd_height'] = $rs['heigth'];
                $arr_goods['memo'] = $v['memo'];  //子sku的memo信息
                $arr_goods['g_updatetime'] = date("Y-m-d H:i:s");

                $arr_goods['g_buyer'] = $rs['developer'];
                $arr_goods['g_checkman'] = $rs['protector'];

                $arr_goods['g_sale_status'] = 1;
                $arr_goods['g_supplier'] = 3; //供货商 外采购
                $arr_goods['standard'] = $rs['sizeinfo'];
                if($rs['p_sellprice']){
                    $arr_goods['g_sellprice'] = $rs['p_sellprice'];
                }
                $arr_goods['g_pd_declare_value'] = 60;


                $arr_goods['g_createID'] = $rs['createID'];
                $arr_goods['g_createUser'] = $rs['createName'];
                $arr_goods['fabricinfo'] = $rs['fabricinfo'];
                if($v["goods_attr_id"]){
                    $arr_goods['g_goodstypeID'] = $v["goods_attr_id"];
                }
                //采购天数
                if($rs['buy_days']){
                    $arr_goods['g_procurement'] = $rs['buy_days'];
                }

                $rs_arr = $this->fun->getdatabasesdetail('db_goods'," AND goods_sku='".trim(strtoupper($v['subsku']))."'");
                if($rs_arr)
                {
                    continue;//如果存在sku则不保存
                }

                $this->db->insert("db_goods",$arr_goods);
                $goods_id = $this->db->insert_id();

                //更新商品属性表 db_goods_attr
                if($v['goods_attr_id']==7){ //衣服
                    $arr_property = unserialize($v['attr_value']);
                    if($arr_property){
                        foreach($arr_property as $kk=>$vv){
                            $arr_goods_attr = array();
                            $arr_goods_attr['goods_id'] = $goods_id;
                            $arr_goods_attr["attr_id"] = $kk;
                            $arr_goods_attr["attr_value"] = $vv;
                            $this->db->insert("db_goods_attr",$arr_goods_attr);
                        }
                    }
                }
                if($v['goods_attr_id']==8){ //鞋子
                    $arr_property = unserialize($v['attr_value']);
                    if($arr_property){
                        foreach($arr_property as $kk=>$vv){
                            $arr_goods_attr = array();
                            $arr_goods_attr['goods_id'] = $goods_id;
                            $arr_goods_attr["attr_id"] = $kk;
                            $arr_goods_attr["attr_value"] = $vv;
                            $this->db->insert("db_goods_attr",$arr_goods_attr);

                        }

                    }
                }
                if($v['goods_attr_id']==12){ //玩具
                    $arr_property = unserialize($v['attr_value']);
                    if($arr_property){
                        foreach($arr_property as $kk=>$vv){
                            $arr_goods_attr = array();
                            $arr_goods_attr['goods_id'] = $goods_id;
                            $arr_goods_attr["attr_id"] = $kk;
                            $arr_goods_attr["attr_value"] = $vv;
                            $this->db->insert("db_goods_attr",$arr_goods_attr);
                        }

                    }
                }



                //插入库存表
                //寻找仓库位置
                $arr_stock = array();
                if(in_array($rs['protector'],$arr_persons)){
                    $key = array_search($rs['protector'],$arr_persons);
                    $arr_stock['positions'] = $arr_positions[$key]; //仓库位置
                }

                $arr_stock['goods_id'] = $goods_id;
                $arr_stock['storage_id']=1;
                $arr_stock['storage_name'] = "一号仓";
                $arr_stock['stock'] = 0;
                $this->db->insert("db_goods_stock",$arr_stock);

                //更新供应商表
                $arr_supplier = array();
                $arr_supplier['parentID']           = $parentID;
                $arr_supplier['goods_id']           = $goods_id;
                $arr_supplier['goods_sku']          = $v['subsku'];
                $arr_supplier['businessman']        = $rs['supplier'];
                $arr_supplier['businessmanline']     = $rs['address'];
                $this->db->insert('db_goods_purchasing',$arr_supplier);

                //更新日志记录
                $goodslog="";
                $goodslog["goods_id"] = $goods_id;	//更新商品表 日志信息
                $goodslog["updatetime"] = date("Y-m-d H:i:s");
                $goodslog["createUid"] = $_COOKIE['userid'];
                $goodslog["types"] = 1;
                $goodslog["content"] = '外采购添加商品,商品sku='.$v['subsku'];
                $goodslog["createUser"] =$_COOKIE['username'];
                $this->db->insert('db_goods_log', $goodslog);

                //更新图片db_goods_images
                if($v["sub_images_url"]){
                    $Imgdata = "";
                    $Imgdata["goods_id"] = $goods_id;
                    $Imgdata["images_type"] = 3;
                    $Imgdata["images_url"] = $v["sub_images_url"];
                    $Imgdata["local_url"] = substr($v["sub_images_url"],1);
                    $Imgdata["thumb_url"] = $v["sub_thumb_url"];
                    $Imgdata["filename"] = $v["filename"];
                    $Imgdata["filesize"] = $v["filesize"];
                    $Imgdata["createUser"] = $_COOKIE["username"];
                    $Imgdata["instime"] = time();
                    $this->db->insert("db_goods_images",$Imgdata);

                }

            }
        }else{

            //更新商品表 商品库存
            $arr_goods = array();
            $arr_goods['goods_parentID'] = $parentID;
            $arr_goods['goods_parent_sku'] = $rs['sku'];
            $arr_goods['goods_sku'] = $rs['sku'];
            $arr_goods['goods_name'] = $rs['p_parent_name'];
            $arr_goods['en_goods_name'] = $rs['p_en_goods_name'];
            $arr_goods['g_bigclassid'] = $rs['p_bigclassid'];
            $arr_goods['g_secondclassid'] = $rs['p_secondclassid'];
            $arr_goods['g_threeclassid'] = $rs['p_threeclassid'];
            $arr_goods['g_costprice'] = $rs['p_costprice'];
            $arr_goods['g_procurement'] = 15;
            $arr_goods['g_procurement'] = 15;
            $arr_goods['g_weight'] =  $rs['weight'];
            $arr_goods['g_pd_length'] = $rs['length'];
            $arr_goods['g_pd_width'] = $rs['width'];
            $arr_goods['g_pd_height'] = $rs['heigth'];
            $arr_goods['memo'] = $rs['memo'];
            $arr_goods['g_updatetime'] = date("Y-m-d H:i:s");

            $arr_goods['g_buyer'] = $rs['developer'];
            $arr_goods['g_checkman'] = $rs['protector'];
            $arr_goods['g_sale_status'] = 1; //销售状态 正常销售
            $arr_goods['g_supplier'] = 3; //供货商 外采购
            $arr_goods['standard'] = $rs['sizeinfo'];

            $arr_goods['g_createID'] = $rs['createID'];
            $arr_goods['g_createUser'] = $rs['createName'];
            $arr_goods['fabricinfo'] = $rs['fabricinfo'];
            if($rs['p_sellprice']){
                $arr_goods['g_sellprice'] = $rs['p_sellprice'];
            }
            $arr_goods['g_pd_declare_value'] = 60;
            //采购天数
            if($rs['buy_days']){
                $arr_goods['g_procurement'] = $rs['buy_days'];
            }

            $rs_arr = $this->fun->getdatabasesdetail('db_goods'," AND goods_sku='".trim(strtoupper($rs['sku']))."'");
            if($rs_arr)
            {
                return $parentID;//如果存在sku则不保存
            }

            $this->db->insert("db_goods",$arr_goods);
            $goods_id = $this->db->insert_id();

            //插入库存表
            //寻找仓库位置
            $arr_stock = array();
            if(in_array($rs['protector'],$arr_persons)){
                $key = array_search($rs['protector'],$arr_persons);
                $arr_stock['positions'] = $arr_positions[$key]; //仓库位置
            }
            $arr_stock['goods_id'] = $goods_id;
            $arr_stock['storage_id']=1;
            $arr_stock['storage_name'] = "一号仓";
            $arr_stock['stock'] = 0;
            $this->db->insert("db_goods_stock",$arr_stock);

            //更新供应商表
            $arr_supplier = array();
            $arr_supplier['parentID']           = $parentID;
            $arr_supplier['goods_id']           = $goods_id;
            $arr_supplier['goods_sku']          = $rs['sku'];
            $arr_supplier['businessman']        = $rs['supplier'];
            $arr_supplier['businessmanline']     = $rs['address'];
            $this->db->insert('db_goods_purchasing',$arr_supplier);

            //更新日志记录
            $goodslog="";
            $goodslog["goods_id"] = $goods_id;	//更新商品表 日志信息
            $goodslog["updatetime"] = date("Y-m-d H:i:s");
            $goodslog["createUid"] = $_COOKIE['userid'];
            $goodslog["types"] = 1;
            $goodslog["content"] = '外采购添加商品,商品sku='.$rs['sku'];
            $goodslog["createUser"] =$_COOKIE['username'];
            $this->db->insert('db_goods_log', $goodslog);

        }


        return $parentID;
    }
    //excel导入相关
    function importExcel($arr_externalbuy){

        $count = 0; //计算实际导入条数
        $date = date("Y-m-d H:i:s");
        $userid = $_COOKIE["userid"];
        $username = $_COOKIE["username"];
        //循环导入相关信息
       foreach($arr_externalbuy as $key=>$value){
           //先判断是否存在！
           $sku = trim($value['sku']);
           //$rs = $this->fun->getdatabasesdetail('db_goods_parent'," AND p_parent_sku='".$sku."'");
           //print_r($rs);exit;
          // if($rs)
          // {
          //    continue; //已经存在的过滤
          // }
           //用户
           $postdata['createTime']		=$date;
           $postdata['createID']		=$userid;
           $postdata['createName']	=$username;

           //保存相关信息
           $p_bigclassid = $this->db->get_where('db_goods_category', "sort_id=0 and cate_name = '{$value['p_bigclassid']}' ")->result_array();
           $postdata['p_bigclassid']  = $p_bigclassid[0]['id'];

           $p_secondclassid = $this->db->get_where('db_goods_category', " sort_id = '{$postdata['p_bigclassid']}' and cate_name = '{$value['p_secondclassid']}' ")->result_array();
           $postdata['p_secondclassid']  = $p_secondclassid[0]['id'];
           //$postdata['p_bigclassid']	= $value['p_bigclassid'];
           //$postdata['p_secondclassid']= $value['p_secondclassid'];
           //$postdata['p_threeclassid'] = $this->input->post('ThreeclassID'); //无三级
           $postdata['sku']	= strtoupper($sku);	//全部大写
           $postdata['p_parent_name']	= $value['p_parent_name'];
           $postdata['p_en_goods_name']	= $value['p_en_goods_name'];
           $postdata['p_costprice']	= $value['p_costprice'];
           $postdata['supplier']  = $value['supplier'];
           //$postdata['contactperson']  =$value['bigclassID']; //没有导入信息
           //$postdata['phone']  =$value['bigclassID']; //没有导入信息
           $postdata['address']  =$value['address'];
           $postdata['sizeinfo']	= $value['sizeinfo'];
           $postdata['fabricinfo']  = $value['fabricinfo'];
           $postdata['memo']  = $value['memo'];

           $postdata['developer']  = $value['developer']; //开发者
           $postdata['protector']  = $value['protector']; //维护者
           //重量 长宽高
           if($value['weight']){
               $postdata['weight'] = $value['weight'];
           }
           if($value['length']){
               $postdata['length'] = $value['length'];
           }
           if($value['width']){
               $postdata['width'] = $value['width'];
           }
           if($value['heigth']){
               $postdata['heigth'] = $value['heigth'];
           }
           $postdata['status']  = 1; //样品采购

           $rsdb = $this->db->get_where('db_external_buy',array('sku' => $sku,'del_flag'=>0))->result_array();
           if(count($rsdb)==0){ //不存在则插入操作
               //插入
               $this->db->query($this->db->insert_string('db_external_buy', $postdata));
               $parentID = $this->db->insert_id();
               $count = $count+1;

               //若图片存在的话，保存图片
               if($value['imagesUrl']){
                   $images_content = @file_get_contents($value['imagesUrl']);
                   $upload_path = 'uploads/externalbuy/'.date("Ymd")."";
                   $dir = dirname(__FILE__) . "/../../".$upload_path;
                   !is_dir($dir) && @mkdir($dir, 0755, true);
                   $filename = date("YmdHms_", time()) . rand(100000, 999999);
                   $file_suffix = ".jpg";
                   $filepath = $upload_path."/".$filename.$file_suffix;

                   $img = array();
                   if(@file_put_contents($filepath, $images_content)>0){
                       $pathst = str_replace(dirname(__FILE__) . "/../../", '',$filepath);
                       $img["images_url"] = "/".$pathst;  //图片文件
                       //生成缩略图
                       $this->load->library('image_lib');
                       $config['image_library'] = 'gd2';
                       $config['source_image'] = $filepath;
                       //print_r($data['thumb']);exit;
                       //$config['new_image'] =  ""; //默认路径在同级目录
                       $config['create_thumb'] = TRUE;
                       $config['maintain_ratio'] = TRUE;
                       $config['width']     = 150;
                       $config['height']   = 150;
                       $this->image_lib->initialize($config);
                       $this->image_lib->resize();
                       $filepath_thumb =  $upload_path."/".$filename."_thumb".$file_suffix;
                       $thumb_url = str_replace(dirname(__FILE__) . "/../../", '',$filepath_thumb);
                       $img["thumb_url"] = "/".$thumb_url;  //缩略图文件

                   }
                   //更新数据表
                   $img["uid"] = $parentID;
                   //$img["images_url"] = $rs;
                   //$img["thumb_url"] = $thumb;
                   $img["createUser"] = $_COOKIE["username"];
                   $img["instime"] = time();
                   $img["filename"] = basename($filepath);
                   $img["filesize"] = filesize($filepath);
                   $this->db->insert('db_externalbuy_images',$img);

               }
               //子商品信息如果存在的话
               if($value['subsku']){
                   $value['subsku'] = str_replace("，",",",$value['subsku']);
                    $arr_subsku = explode(",",$value['subsku']);
                   $this->saveExternalBuygoods($parentID,$buyId = "",$arr_subsku); //更新相关子sku信息
               }

               //追加日志信息
               $msg = "excel导入外采购商品";
               $arr_logs['createtime'] = date("Y-m-d H:i:s");
               $arr_logs['pid'] = $parentID;
               $arr_logs['goods_code'] = $postdata['sku'];
               $arr_logs['details'] = $msg;
               $arr_logs['username'] = $_COOKIE['username'];
               $arr_logs['userid'] = $_COOKIE['userid'];
               $this->db->insert('db_externalbuy_log', $arr_logs);
           }else{
               continue;
           }

       }
       return $count; //返回导入的外采购商品数

    }
    function getProductImages($id,$type=0)
    {
        if(!$type){
            $type = 0;
        }
        $result = $this->db->get_where('db_externalbuy_images', " type= '{$type}' AND  uid = '".$id."'")->result_array();
        if(count($result)>0)
        {
            return $result;
        }
    }
    function saveProductImages($type=0)
    {
        $filepath = $this->input->post('filepath');
        $filethumbpath = $this->input->post('filethumbpath');
        if(count($filepath)>0)
        {
            foreach($filepath as $key=>$rs)
            {
                $thumb =  $filethumbpath[$key];
                $dir = dirname(__FILE__) . "/../..".$rs;
                $img = array();
                $img["uid"] = $this->input->post('MergeProductID');
                $img["images_url"] = $rs;
                $img["thumb_url"] = $thumb;
                $img["createUser"] = $_COOKIE["username"];
                $img["instime"] = time();
                $img["filename"] = basename($dir);
                $img["filesize"] = filesize($dir);
                if(!$type){
                    $type = 0;
                }
                $img["type"] = $type;
                $this->db->insert('db_externalbuy_images',$img);

            }
        }
        return $this->input->post('MergeProductID');

    }

	function saveMaintenanceSKU($goodsparentID)
	{
		$rsdb = $this->fun->getdatabasesdetail("db_goods"," AND goods_parentID ='".intval($goodsparentID)."' ","GROUP_CONCAT(goods_id) as goods_id ");
		$parent = $this->fun->getdatabasesdetail("db_goods_parent"," AND p_parent_id ='".intval($goodsparentID)."' ");
		$res =  $this->fun->getdatabasesdetail("db_external_buy"," AND sku ='".$parent['p_parent_sku']."' ");
		if($res)
		{
			$db_external_buy_id = $res["id"];
		}


		$goodsList = $this->fun->getdatabasesdetail("db_goods"," AND goods_parentID ='".intval($goodsparentID)."' ","g_buyer");
		$post="";
		$post['p_bigclassid'] = $parent['p_bigclassid'];
		$post['p_secondclassid'] = $parent['p_secondclassid'];
		$post['p_threeclassid'] = $parent['p_threeclassid'];
		$post['sku'] = $parent['p_parent_sku'];
		$post['p_parent_name'] = $parent['p_parent_name'];
		$post['p_en_goods_name'] = $parent['p_en_goods_name'];
		$post['status'] = 99;
		$post['p_costprice'] = $parent['p_costprice'];
		$post['p_sellprice'] = $parent['p_sellprice'];
		$post['weight'] = $parent['p_weight'];
		$post['length'] = $parent['p_pd_length'];
		$post['width'] = $parent['p_pd_width'];
		$post['heigth'] = $parent['p_pd_height'];
		$post['sizeinfo'] = $parent['standard'];
		$post['fabricinfo'] = $parent['fabricinfo'];
		$post['memo'] = '';
		$post['supplier'] = $parent['businessman'];
		$post['address'] = $parent['businessmanline'];
		$post['overuser'] =$_COOKIE['username'];
		$post['overtime'] = time();
		$post['developer'] = $goodsList['g_checkman']?$goodsList['g_checkman']:$_COOKIE['username'];
		$post['protector'] = $_COOKIE['username'];
		$post['createID'] = $_COOKIE['userid'];
		$post['createName'] = $_COOKIE['username'];
		$post['finishTime'] = date("Y-m-d H:i:s");
		$post['createTime'] = date("Y-m-d H:i:s");
		$post['del_flag'] = 0;
		$post['types'] = 1;

        //获取外采购商品开发人员对应的仓库
        $str_warehouse = $this->config->item('temporary_warehouse');
        $arr_warehouse = explode("\n",$str_warehouse);
        $arr_persons = array(); //维护人员
        $arr_positions = array();//具体仓库位置
        foreach($arr_warehouse as $k=>$v){
            $arr_value = explode("|",trim($v));
            $arr_persons[$k] = $arr_value[0];
            $arr_positions[$k]=$arr_value[1];
        }
        $positions = "";
        if(in_array($_COOKIE['username'],$arr_persons)){
            $key = array_search($_COOKIE['username'],$arr_persons);
            $positions = $arr_positions[$key]; //仓库位置
        }

//		if($positions=='R.2.1')
//		{
//			$positions ='';
//		}

		
		$this->db->trans_begin();
			if($db_external_buy_id)
			{
			
			}else{
				$this->db->insert('db_external_buy', $post);
				$id = $this->db->insert_id();
				if($rsdb["goods_id"]){
					$goods_id = $rsdb["goods_id"];
					$goods_images = $this->db->get_where('db_goods_images', " goods_id in($goods_id)")->result_array();

					if(count($goods_images) >0)
					{
						$postimages="";
						foreach($goods_images as $key=>$rs)
						{
							$postimages[$key]["uid"] = $id;
							$postimages[$key]["images_url"] = $rs['images_url'];
							$postimages[$key]["thumb_url"] = $rs["thumb_url"];
							$postimages[$key]["filename"] = $rs['filename'];
							$postimages[$key]["filesize"] = $rs["filesize"];
							$postimages[$key]["createUser"] = $rs['createUser'];
							$postimages[$key]["instime"] = $rs["instime"];
						}
						$this->db->insert_batch('db_externalbuy_images',$postimages);
					}
				}
			}
		
		//存图片
		if($rsdb["goods_id"]){
			$goods_id = $rsdb["goods_id"];
			$goodsdb =explode(",",$goods_id);
			foreach($goodsdb as $key=>$rgoods)
			{
				$resGoods =  $this->fun->getdatabasesdetail("db_goods"," AND goods_id ='".$rgoods."' ");
				$rval="原采购人员：".$resGoods["g_buyer"]." 更新为：".$_COOKIE["username"]."";
				$rval.=" 原维护：".$resGoods["g_checkman"]." 更新为：".$_COOKIE["username"]."";
				
				$this->fun->goods_update_log($rgoods,$rval,1);	//更新商品信息

                //更新相关仓位
                if($positions){
                    $sql_stock = "SELECT * FROM db_goods_stock WHERE storage_id = 1 AND goods_id = '{$rgoods}' ";
                    $rs_stock  = $this->db->query($sql_stock)->row_array();
                    if(count($rs_stock)>0){
                        if(!$rs_stock['positions']){
                            $this->db->update('db_goods_stock',array("positions"=>$positions)," storage_id = 1 AND goods_id = '".$rgoods."'");
                        }else{
                            if(in_array($rs_stock['positions'],$arr_positions)){
                                $this->db->update('db_goods_stock',array("positions"=>$positions)," storage_id = 1 AND goods_id = '".$rgoods."'");
                            }else{
                                //不做更新，可能仓位已经设定
                            }
                        }

                    }
                }//仓位 endif


			}
			
		}

		$this->db->update("db_goods",array("g_buyer"=>$_COOKIE['username'],"g_checkman"=>$_COOKIE['username']),"goods_parentID ='".intval($goodsparentID)."'");
		$this->db->update("db_goods_parent",array("p_buyer"=>$_COOKIE['username'],"p_checkman"=>$_COOKIE['username']),"p_parent_id ='".intval($goodsparentID)."'");
		


		if ($this->db->trans_status() === FALSE)
		{
			$this->db->trans_rollback();
		}
		else
		{
			$this->db->trans_commit();
		}

		return;



	}


}

